<template>
  <div class="alert-center">
    <!-- Page Header -->
    <div class="page-header">
      <div>
        <h1 class="page-title">Alert Center</h1>
        <p class="page-subtitle">Intelligent Alert Management and Analysis</p>
      </div>
      <a-space>
        <a-button @click="refreshData">
          <template #icon><ReloadOutlined :spin="loading" /></template>
          Refresh
        </a-button>
        <a-button type="primary">
          <template #icon><PlusOutlined /></template>
          Create Alert Rule
        </a-button>
      </a-space>
    </div>

    <!-- Statistics Cards -->
    <a-row :gutter="[16, 16]" class="mb-4">
      <a-col :xs="24" :sm="12" :lg="6" v-for="stat in alertStats" :key="stat.label">
        <div class="alert-stat-card" :class="`alert-stat-${stat.type}`" @click="filterByStatus(stat.filter)">
          <div class="stat-icon" :style="{ background: stat.gradient }">
            <component :is="stat.icon" />
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
          <div class="stat-chart">
            <div class="mini-chart" :style="{ background: stat.gradient }" />
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- Filters -->
    <a-card :bordered="false" class="filter-card mb-4">
      <a-space wrap>
        <a-select
          v-model:value="filters.status"
          placeholder="Status"
          style="width: 150px"
          allow-clear
          @change="handleFilterChange"
        >
          <a-select-option value="firing">
            <a-badge status="error" text="Firing" />
          </a-select-option>
          <a-select-option value="resolved">
            <a-badge status="success" text="Resolved" />
          </a-select-option>
          <a-select-option value="acknowledged">
            <a-badge status="processing" text="Acknowledged" />
          </a-select-option>
        </a-select>

        <a-select
          v-model:value="filters.severity"
          placeholder="Severity"
          style="width: 150px"
          allow-clear
          @change="handleFilterChange"
        >
          <a-select-option value="critical">
            <a-tag color="red" style="margin: 0">Critical</a-tag>
          </a-select-option>
          <a-select-option value="high">
            <a-tag color="orange" style="margin: 0">High</a-tag>
          </a-select-option>
          <a-select-option value="medium">
            <a-tag color="gold" style="margin: 0">Medium</a-tag>
          </a-select-option>
          <a-select-option value="low">
            <a-tag color="green" style="margin: 0">Low</a-tag>
          </a-select-option>
        </a-select>

        <a-input-search
          v-model:value="filters.search"
          placeholder="Search alert name, instance..."
          style="width: 300px"
          @search="handleFilterChange"
          allow-clear
        />

        <a-range-picker
          v-model:value="filters.dateRange"
          style="width: 280px"
          :placeholder="['Start Date', 'End Date']"
          @change="handleFilterChange"
        />

        <a-button @click="resetFilters">
          <template #icon><ClearOutlined /></template>
          Reset
        </a-button>
      </a-space>
    </a-card>

    <!-- Alert List -->
    <a-card :bordered="false" class="table-card">
      <a-table
        :columns="columns"
        :data-source="filteredAlerts"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :row-class-name="rowClassName"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <div class="alert-name-cell">
              <strong>{{ record.name }}</strong>
              <div class="alert-instance">{{ record.instance }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'severity'">
            <a-tag :color="getSeverityColor(record.severity)" class="severity-tag">
              <template #icon>
                <WarningOutlined v-if="record.severity === 'critical'" />
                <ExclamationCircleOutlined v-else />
              </template>
              {{ getSeverityText(record.severity) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-badge :status="getStatusBadge(record.status)">
              <span class="status-text">{{ getStatusText(record.status) }}</span>
            </a-badge>
          </template>

          <template v-else-if="column.key === 'startTime'">
            <div class="time-cell">
              <ClockCircleOutlined class="time-icon" />
              {{ record.startTime }}
            </div>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-tooltip title="View Details">
                <a-button type="text" size="small" @click="viewAlert(record)">
                  <template #icon><EyeOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="Acknowledge Alert">
                <a-button type="text" size="small" @click="acknowledgeAlert(record)">
                  <template #icon><CheckOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip title="Mute">
                <a-button type="text" size="small" @click="muteAlert(record)">
                  <template #icon><BellOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- Alert Details Modal -->
    <a-modal
      v-model:open="detailVisible"
      :title="selectedAlert?.alertname"
      width="900px"
    >
      <template #footer>
        <a-space>
          <a-button @click="detailVisible = false">Close</a-button>
          <a-button
            type="primary"
            :loading="creatingTicket"
            @click="createTicketFromAlert"
          >
            <template #icon><FileAddOutlined /></template>
            Create Ticket
          </a-button>
        </a-space>
      </template>
      <div v-if="selectedAlert" class="alert-detail">
        <!-- Basic Information -->
        <div class="detail-section">
          <h3 class="section-title" style="margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #f3f4f6;">Basic Information</h3>
          <a-descriptions bordered :column="2">
            <a-descriptions-item label="Alert Name">
              {{ selectedAlert.alertname }}
            </a-descriptions-item>
            <a-descriptions-item label="Severity">
              <a-tag :color="getSeverityColor(selectedAlert.severity)">
                {{ getSeverityText(selectedAlert.severity) }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="Status">
              <a-badge :status="getStatusBadge(selectedAlert.status === 'active' ? 'firing' : selectedAlert.status)">
                <span>{{ getStatusText(selectedAlert.status === 'active' ? 'firing' : selectedAlert.status) }}</span>
              </a-badge>
            </a-descriptions-item>
            <a-descriptions-item label="Instance">
              {{ selectedAlert.instance }}
            </a-descriptions-item>
            <a-descriptions-item label="Job">
              {{ selectedAlert.job }}
            </a-descriptions-item>
            <a-descriptions-item label="Start Time">
              {{ dayjs(selectedAlert.startsAt).format('YYYY-MM-DD HH:mm:ss') }}
            </a-descriptions-item>
            <a-descriptions-item label="Duration" :span="2">
              {{ dayjs(selectedAlert.startsAt).fromNow() }}
            </a-descriptions-item>
            <a-descriptions-item label="Description" :span="2">
              {{ selectedAlert.description }}
            </a-descriptions-item>
          </a-descriptions>
        </div>

        <!-- AI Analysis -->
        <div class="detail-section">
          <div class="section-header">
            <h3 class="section-title">AI Analysis</h3>
            <a-button
              v-if="!selectedAlert.aiAnalysis"
              type="primary"
              :loading="aiAnalyzing"
              @click="triggerAIAnalysis"
              size="small"
            >
              <template #icon><ThunderboltOutlined /></template>
              AI Analysis
            </a-button>
          </div>

          <a-card v-if="selectedAlert.aiAnalysis" class="ai-analysis-card">
            <div class="analysis-item">
              <div class="analysis-label">Summary</div>
              <div class="analysis-content">{{ selectedAlert.aiAnalysis.summary }}</div>
            </div>
            <a-divider />
            <div class="analysis-item">
              <div class="analysis-label">Root Cause Analysis</div>
              <div class="analysis-content">{{ selectedAlert.aiAnalysis.rootCause }}</div>
            </div>
            <a-divider />
            <div class="analysis-item">
              <div class="analysis-label">Recommended Actions</div>
              <ul class="suggestions-list">
                <li v-for="(suggestion, index) in selectedAlert.aiAnalysis.suggestions" :key="index">
                  {{ suggestion }}
                </li>
              </ul>
            </div>
            <a-divider />
            <div class="analysis-item">
              <div class="analysis-label">Confidence</div>
              <a-progress :percent="selectedAlert.aiAnalysis.confidence * 100" :show-info="true" />
            </div>
            <a-divider v-if="selectedAlert.aiAnalysis.tags?.length" />
            <div v-if="selectedAlert.aiAnalysis.tags?.length" class="analysis-item">
              <div class="analysis-label">Tags</div>
              <a-space wrap>
                <a-tag v-for="tag in selectedAlert.aiAnalysis.tags" :key="tag" color="blue">
                  {{ tag }}
                </a-tag>
              </a-space>
            </div>
          </a-card>

          <a-empty v-else description="Click the button above to start AI analysis" />
        </div>

        <!-- Labels -->
        <div class="detail-section">
          <h3 class="section-title" style="margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #f3f4f6;">Labels</h3>
          <a-space wrap>
            <a-tag v-for="(value, key) in selectedAlert.labels" :key="key">
              <strong>{{ key }}:</strong> {{ value }}
            </a-tag>
          </a-space>
        </div>

        <!-- Annotations -->
        <div class="detail-section">
          <h3 class="section-title" style="margin-bottom: 16px; padding-bottom: 8px; border-bottom: 2px solid #f3f4f6;">Annotations</h3>
          <a-space wrap>
            <a-tag v-for="(value, key) in selectedAlert.annotations" :key="key" color="purple">
              <strong>{{ key }}:</strong> {{ value }}
            </a-tag>
          </a-space>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  ReloadOutlined,
  ClearOutlined,
  BellOutlined,
  FireOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  CheckOutlined,
  ThunderboltOutlined,
  FileAddOutlined,
} from '@ant-design/icons-vue'
import { getAlerts, getAlertStatistics, analyzeAlertWithAI, type Alert } from '@/api/alert'
import { createTicket } from '@/api/ticket'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'

dayjs.extend(relativeTime)

const router = useRouter()
const loading = ref(false)
const detailVisible = ref(false)
const selectedAlert = ref<Alert | null>(null)
const aiAnalyzing = ref(false)
const creatingTicket = ref(false)

const filters = reactive({
  status: undefined,
  severity: undefined,
  search: '',
  dateRange: undefined,
})

const alertStats = ref([
  {
    label: 'Active Alerts',
    value: 23,
    type: 'firing',
    filter: 'firing',
    icon: FireOutlined,
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  },
  {
    label: 'Resolved',
    value: 156,
    type: 'resolved',
    filter: 'resolved',
    icon: CheckCircleOutlined,
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  },
  {
    label: 'Pending',
    value: 8,
    type: 'pending',
    filter: 'firing',
    icon: ClockCircleOutlined,
    gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
  },
  {
    label: 'Muted',
    value: 12,
    type: 'muted',
    filter: '',
    icon: BellOutlined,
    gradient: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
  },
])

const columns = [
  { title: 'Alert Name', dataIndex: 'name', key: 'name', width: 250, fixed: 'left' },
  { title: 'Severity', dataIndex: 'severity', key: 'severity', width: 120 },
  { title: 'Status', dataIndex: 'status', key: 'status', width: 120 },
  { title: 'Start Time', dataIndex: 'startTime', key: 'startTime', width: 180 },
  { title: 'Duration', dataIndex: 'duration', key: 'duration', width: 120 },
  { title: 'Actions', key: 'action', width: 150, fixed: 'right' },
]

const alerts = ref<Alert[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 5,
  showSizeChanger: true,
  showTotal: (total: number) => `Total ${total} items`,
})

const filteredAlerts = computed(() => {
  if (!alerts.value) return []
  return alerts.value.map(alert => ({
    key: alert.id,
    name: alert.alertname,
    severity: alert.severity,
    status: alert.status === 'active' ? 'firing' : alert.status,
    instance: alert.instance,
    startTime: dayjs(alert.startsAt).format('YYYY-MM-DD HH:mm:ss'),
    duration: dayjs(alert.startsAt).fromNow(),
    ...alert,
  }))
})

const getSeverityColor = (severity: string) => {
  const colors: Record<string, string> = {
    critical: 'red',
    high: 'orange',
    medium: 'gold',
    low: 'green',
  }
  return colors[severity] || 'default'
}

const getSeverityText = (severity: string) => {
  const texts: Record<string, string> = {
    critical: 'Critical',
    high: 'High',
    medium: 'Medium',
    low: 'Low',
  }
  return texts[severity] || severity
}

const getStatusBadge = (status: string) => {
  const badges: Record<string, any> = {
    firing: 'error',
    resolved: 'success',
    acknowledged: 'processing',
  }
  return badges[status] || 'default'
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    firing: 'Firing',
    resolved: 'Resolved',
    acknowledged: 'Acknowledged',
  }
  return texts[status] || status
}

const rowClassName = (record: any) => {
  if (record.severity === 'critical') return 'critical-row'
  if (record.status === 'firing') return 'firing-row'
  return ''
}

const filterByStatus = (status: string) => {
  filters.status = status || undefined
  handleFilterChange()
}

const handleFilterChange = () => {
  pagination.current = 1
  loadAlerts()
}

const resetFilters = () => {
  filters.status = undefined
  filters.severity = undefined
  filters.search = ''
  filters.dateRange = undefined
  handleFilterChange()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadAlerts()
}

// Load alert data
const loadAlerts = async () => {
  loading.value = true
  try {
    const response = await getAlerts({
      status: filters.status,
      severity: filters.severity,
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: filters.search,
    })

    alerts.value = response.data
    pagination.total = response.pagination.total

    // Update statistics data
    await loadStatistics()
  } catch (error) {
    console.error('Failed to load alerts:', error)
  } finally {
    loading.value = false
  }
}

// Load statistics data
const loadStatistics = async () => {
  try {
    const response = await getAlertStatistics()
    const stats = response.data

    alertStats.value = [
      {
        label: 'Active Alerts',
        value: stats.active || 0,
        type: 'firing',
        filter: 'firing',
        icon: FireOutlined,
        gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
      },
      {
        label: 'Resolved',
        value: stats.resolved || 0,
        type: 'resolved',
        filter: 'resolved',
        icon: CheckCircleOutlined,
        gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
      },
      {
        label: 'Critical',
        value: stats.critical || 0,
        type: 'critical',
        filter: 'firing',
        icon: WarningOutlined,
        gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
      },
      {
        label: 'Total',
        value: stats.total || 0,
        type: 'total',
        filter: '',
        icon: BellOutlined,
        gradient: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
      },
    ]
  } catch (error) {
    console.error('Failed to load statistics:', error)
  }
}

const refreshData = () => {
  loadAlerts()
  message.success('Refreshed successfully')
}

const viewAlert = (record: any) => {
  selectedAlert.value = alerts.value.find(a => a.id === record.key) || null
  detailVisible.value = true
}

const acknowledgeAlert = async (record: any) => {
  message.success(`Alert acknowledged: ${record.name}`)
  await loadAlerts()
}

const muteAlert = (record: any) => {
  message.success(`Alert muted: ${record.name}`)
}

// AI alert analysis
const triggerAIAnalysis = async () => {
  if (!selectedAlert.value) return

  aiAnalyzing.value = true
  try {
    const response = await analyzeAlertWithAI(selectedAlert.value.id)

    // Update AI analysis results for selected alert
    if (selectedAlert.value) {
      selectedAlert.value.aiAnalysis = response.data
    }

    // Also update data in alerts list
    const alertIndex = alerts.value.findIndex(a => a.id === selectedAlert.value?.id)
    if (alertIndex !== -1) {
      alerts.value[alertIndex].aiAnalysis = response.data
    }

    message.success('AI analysis completed')
  } catch (error) {
    console.error('AI analysis failed:', error)
    message.error('AI analysis failed, please retry')
  } finally {
    aiAnalyzing.value = false
  }
}

// Create ticket from alert
const createTicketFromAlert = async () => {
  if (!selectedAlert.value) return

  creatingTicket.value = true
  try {
    // Determine priority based on severity
    const priorityMap: Record<string, string> = {
      critical: 'critical',
      high: 'high',
      medium: 'medium',
      low: 'low',
    }
    const priority = priorityMap[selectedAlert.value.severity] || 'medium'

    // Create ticket payload
    const ticketData = {
      title: `Alert: ${selectedAlert.value.alertname}`,
      description: `**Alert Details**\n\n` +
        `- **Instance**: ${selectedAlert.value.instance}\n` +
        `- **Job**: ${selectedAlert.value.job}\n` +
        `- **Severity**: ${selectedAlert.value.severity}\n` +
        `- **Start Time**: ${dayjs(selectedAlert.value.startsAt).format('YYYY-MM-DD HH:mm:ss')}\n\n` +
        `**Description**: ${selectedAlert.value.description || 'N/A'}\n\n` +
        (selectedAlert.value.aiAnalysis ?
          `**AI Analysis**\n\n` +
          `**Summary**: ${selectedAlert.value.aiAnalysis.summary}\n\n` +
          `**Root Cause**: ${selectedAlert.value.aiAnalysis.rootCause}\n\n` +
          `**Recommended Actions**:\n${selectedAlert.value.aiAnalysis.suggestions?.map((s: string) => `- ${s}`).join('\n')}`
          : ''),
      priority,
      relatedAlertId: selectedAlert.value.id,
    }

    const response = await createTicket(ticketData)

    message.success('Ticket created successfully')
    detailVisible.value = false

    // Navigate to ticket detail page
    router.push(`/tickets/${response.ticket.id}`)
  } catch (error: any) {
    console.error('Failed to create ticket:', error)
    message.error(error.message || 'Failed to create ticket')
  } finally {
    creatingTicket.value = false
  }
}

// Load data on component mount
onMounted(() => {
  // Only fetch if we don't have alerts data yet
  if (alerts.value.length === 0) {
    loadAlerts()
  }
})
</script>

<style scoped>
.alert-center {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-subtitle {
  margin: 4px 0 0;
  font-size: 14px;
  color: #6b7280;
}

.alert-stat-card {
  position: relative;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
}

.alert-stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px -8px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  font-size: 24px;
  color: white;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stat-info {
  flex: 1;
  min-width: 0;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.stat-chart {
  width: 60px;
  height: 40px;
  position: relative;
}

.mini-chart {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  opacity: 0.1;
  border-radius: 4px;
}

.filter-card {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  border-radius: 12px;
}

.filter-card :deep(.ant-card-body) {
  padding: 16px 24px;
}

.table-card {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  border-radius: 12px;
}

.table-card :deep(.ant-card-body) {
  padding: 0;
}

.table-card :deep(.ant-table) {
  border-radius: 12px;
}

.alert-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.alert-instance {
  font-size: 12px;
  color: #9ca3af;
}

.severity-tag {
  font-weight: 500;
}

.status-text {
  font-size: 14px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #6b7280;
}

.time-icon {
  font-size: 14px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* Table row styles */
:deep(.critical-row) {
  background: #fff1f0 !important;
}

:deep(.firing-row) {
  background: #fffbe6 !important;
}

:deep(.critical-row:hover),
:deep(.firing-row:hover) {
  background: #fafafa !important;
}

:deep(.ant-table-row) {
  transition: all 0.2s ease;
}

:deep(.ant-table-row:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* Alert detail modal styles */
.alert-detail {
  padding: 8px 0;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f3f4f6;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.ai-analysis-card {
  background: linear-gradient(135deg, #f6f8fb 0%, #fefefe 100%);
  border: 1px solid #e5e7eb;
}

.analysis-item {
  margin: 8px 0;
}

.analysis-label {
  font-size: 14px;
  font-weight: 600;
  color: #4b5563;
  margin-bottom: 8px;
}

.analysis-content {
  font-size: 14px;
  color: #1f2937;
  line-height: 1.6;
}

.suggestions-list {
  margin: 0;
  padding-left: 20px;
  color: #1f2937;
}

.suggestions-list li {
  margin: 6px 0;
  line-height: 1.6;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 600;
  background: #f9fafb;
}

:deep(.ant-modal-header) {
  border-bottom: 2px solid #f3f4f6;
}

:deep(.ant-modal-title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}
</style>
